﻿using MongoDB.Driver;
using System;
using System.Threading.Tasks;
using NetMicro.Domains;

namespace NetMicro.MongoProvider
{
    /// <summary>
    /// public interface IMongoProvider
    /// </summary>
    public class MongoDBTransaction : IDisposable
    {
        private readonly MongoClient _client;
        private IClientSessionHandle clientSessionHandle;

        public MongoDBTransaction(MongoClient client)
        {
            _client = client;
        }

        /// <summary>
        /// 开始事务
        /// </summary>
        /// <returns></returns>
        public async Task<IClientSessionHandle> StartTransactionAsync()
        {
            clientSessionHandle = await _client.StartSessionAsync();
            clientSessionHandle.StartTransaction();
            return clientSessionHandle;
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public async Task CommitTransactionAsync()
        {
            await clientSessionHandle.CommitTransactionAsync();
        }
        /// <summary>
        /// 终止事务
        /// </summary>
        /// <returns></returns>
        public async Task AbortTransactionAsync()
        {
            await clientSessionHandle.AbortTransactionAsync();
        }

        public void Dispose()
        {
            try
            {
                if (clientSessionHandle?.IsInTransaction ?? false)
                {
                    clientSessionHandle.CommitTransaction();
                }
            }
            finally
            {
                if (clientSessionHandle?.IsInTransaction ?? false)
                {
                    clientSessionHandle.AbortTransaction();
                }
            }
        }
    }
}
